package com.msb.juc.c_020;

import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;

public class T11_Exchanger {


    static Exchanger<String> exchanger = new Exchanger<>();


    public static void main(String[] args) {
        /*
        用于线程间交换数据
        交换过程为阻塞执行
        如果没能换到，就一直等着
        */
        new Thread(() -> {
            String s = "T1";
            try {
                s = exchanger.exchange(s);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " " + s);
        }, "t1").start();

        new Thread(() -> {
            String s = "T2";
            try {
                TimeUnit.SECONDS.sleep(2);
                s = exchanger.exchange(s);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " " + s);
        }, "t2").start();
    }
}
